//
//  UIButton+countdownTime.m
//  countdownTime
//
//  Created by Alfa Li on 2018/5/17.
//  Copyright © 2018年 Alfa Li. All rights reserved.
//

#import "UIButton+countdownTime.h"

static NSString *normelText;
static UIColor *normelColor;

@implementation UIButton (countdownTime)

- (void)startCountdownTime:(int )time withCountDownBlock:(CountDownTimeBlock )block
{
    [self initButtonData];
    
    [self startCountDownTime:time];
    
    if (block) {
        block();
    }
    
}

- (void)initButtonData
{
    normelText = [NSString stringWithFormat:@"%@",self.titleLabel.text];
    
}

- (void)startCountDownTime:(int )time
{
    
    __block int timeout = time;
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0 * NSEC_PER_SEC, 0);
    
    dispatch_source_set_event_handler(_timer, ^{
        
        //倒计时结束
        if(timeout <= 0){
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self setTitle:normelText forState:UIControlStateNormal];
                
                [self setAlpha:1];
                
                self.titleLabel.font = [UIFont systemFontOfSize:12];
                self.layer.backgroundColor = [UIColor whiteColor].CGColor;
                
                self.enabled = YES;
                
//                [self setSelected:NO];
                
            });
            
        }else{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSString *text = [NSString stringWithFormat:@"%02d秒后重新获取",timeout];
                
                self.titleLabel.font = [UIFont systemFontOfSize:10];
//                self.layer.backgroundColor = [UIColor lightGrayColor].CGColor;
                //禁止隐式动画
                [UIView performWithoutAnimation:^{
                    [self setTitle:text forState:UIControlStateDisabled];
                    [self layoutIfNeeded];
                }];
//                [self setTitle:text forState:UIControlStateDisabled];
                
                [self setAlpha:0.7];
                
                self.enabled = NO;
                
//                [self setSelected:YES];
                
            });
            
            timeout --;
        }
        
    });
    
    dispatch_resume(_timer);
    
}



@end
